package com.cl.common;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Filter301 implements Filter {

    protected String encoding = null;

    protected FilterConfig filterConfig = null;

    protected boolean ignore = true;


    // --------------------------------------------------------- Public Methods

    public void destroy() {

        this.encoding = null;
        this.filterConfig = null;

    }

    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain)
	throws IOException, ServletException {
    	HttpServletResponse httpResponse=(HttpServletResponse)response;
    	HttpServletRequest httpRequest=(HttpServletRequest)request;
    	//取得完整请求url-------------------
//    	String strBackUrl = "http://" + httpRequest.getServerName() + ":" + httpRequest.getServerPort() + httpRequest.getContextPath() + httpRequest.getServletPath() + "?" + this.codeToString(httpRequest.getQueryString());
        //------------------------------------
        // Conditionally select and set the http301 redirect to be used   
    	String redirectUrl ="";
//    	System.out.println("http://www." + httpRequest.getServerName());
    	if(!httpRequest.getServerName().startsWith("www.")){
	    	redirectUrl = "http://www." + httpRequest.getServerName();
	    	if(httpRequest.getServerPort()!=80){
	    		redirectUrl += ":" + httpRequest.getServerPort();
	    	}
	    	redirectUrl += httpRequest.getRequestURI();
	    	//redirectUrl += httpRequest.getContextPath() + httpRequest.getServletPath();
	    	if(!( httpRequest.getQueryString()==null || "".equals(httpRequest.getQueryString()) )){
	    		redirectUrl+="?" + this.codeToString(httpRequest.getQueryString());
	    	}
	    	httpResponse.setStatus(301);
        	httpResponse.setHeader( "Location", redirectUrl);
//        	System.out.println("redirectUrl="+redirectUrl);
        	httpResponse.setHeader( "Connection", "close" );
        	return;
    	}
 
	// Pass control on to the next filter
        chain.doFilter(request, response);

    }

    public void init(FilterConfig filterConfig) throws ServletException {

    }
    public  String codeToString(String str) {
        String strString = str;
        try {
            byte tempB[] = strString.getBytes("ISO-8859-1");
            strString = new String(tempB);
            return strString;
        } catch (Exception e) {
            return strString;
        }
    } 
}

	